import { Injectable } from '@nestjs/common'
import { DataSource } from 'typeorm'

/**
 * 通用动态CRUD服务
 * 支持任意模型的增删改查
 */
@Injectable()
export class CrudService<T> {
  constructor(private readonly dataSource: DataSource) {}

  /** 获取列表 */
  async list(model: string, query: any) {
    const table = model.toLowerCase()
    // 可扩展分页、条件等
    return this.dataSource.query(`SELECT * FROM \`${table}\``)
  }

  /** 获取详情 */
  async detail(model: string, id: string) {
    const table = model.toLowerCase()
    const rows = await this.dataSource.query(`SELECT * FROM \`${table}\` WHERE id = ?`, [id])
    return rows[0]
  }

  /** 新增 */
  async create(model: string, data: any) {
    const table = model.toLowerCase()
    data.id = data.id || Math.random().toString(36).slice(2) + Date.now()
    await this.dataSource.query(
      `INSERT INTO \`${table}\` (${Object.keys(data)
        .map((k) => `\`${k}\``)
        .join(',')}) VALUES (${Object.keys(data)
        .map(() => '?')
        .join(',')})`,
      Object.values(data),
    )
    return data
  }

  /** 更新 */
  async update(model: string, id: string, data: any) {
    const table = model.toLowerCase()
    const sets = Object.keys(data)
      .map((k) => `\`${k}\` = ?`)
      .join(',')
    await this.dataSource.query(`UPDATE \`${table}\` SET ${sets} WHERE id = ?`, [...Object.values(data), id])
    return { id, ...data }
  }

  /** 删除 */
  async remove(model: string, id: string) {
    const table = model.toLowerCase()
    await this.dataSource.query(`DELETE FROM \`${table}\` WHERE id = ?`, [id])
    return { id }
  }
}
